package xgorm

import (
	"encoding/json"
	"errors"
	"strings"
)

// 获取int类型字段值
//
//	field	获取的字段值
func (c *XDB) ValueInt64(field string) int64 {
	switch c.DB.Dialector.Name() {
	case "mysql":
		field = "CAST(" + field + " AS SIGNED) AS val"
	case "sqlserver":
		field = "CAST(" + field + " AS INT) AS val"
	case "sqlite", "postgres":
		field = "CAST(" + field + " AS INTEGER) AS val"
	default:
		return 0
	}
	var id int64
	err := c.Select(field).Limit(1).Find(&id).Error
	if err != nil {
		return 0
	}
	return id
}

// 获取float类型字段值
//
//	field	获取的字段值
func (c *XDB) ValueFloat64(field string) float64 {
	switch c.DB.Dialector.Name() {
	case "mysql":
		field = "CAST(" + field + " AS DOUBLE) AS val"
	case "sqlserver", "postgres":
		field = "CAST(" + field + " AS FLOAT) AS val"
	case "sqlite":
		field = "CAST(" + field + " AS REAL) AS val"
	default:
		return 0
	}
	var id float64
	err := c.Select(field).Limit(1).Find(&id).Error
	if err != nil {
		return 0
	}
	return id
}

// 获取字段的字符串值
//
//	field	获取的字段值
func (c *XDB) ValueString(field string) string {
	switch c.DB.Dialector.Name() {
	case "mysql":
		field = "CAST(" + field + " AS CHAR) AS val"
	case "sqlserver":
		field = "CAST(" + field + " AS VARCHAR(99999)) AS val"
	case "sqlite", "postgres":
		field = "CAST(" + field + " AS TEXT) AS val"
	default:
		return ""
	}
	var id string
	err := c.Select(field).Limit(1).Find(&id).Error
	if err != nil {
		return ""
	}
	return id
}

// 获取字段的JSON值，会解析到jsons变量中去
//
//	field	获取的字段值
//	jsons	待解析的值
func (c *XDB) ValueJson(field string, jsons any) error {
	switch c.DB.Dialector.Name() {
	case "mysql":
		field = "CAST(" + field + " AS CHAR) AS val"
	case "sqlserver":
		field = "CAST(" + field + " AS VARCHAR(99999)) AS val"
	case "sqlite", "postgres":
		field = "CAST(" + field + " AS TEXT) AS val"
	default:
		return errors.New("抱歉，暂不支持该类型数据库的字符串类型提取")
	}
	var id string
	err := c.Select(field).Limit(1).Find(&id).Error
	if err != nil {
		return err
	}
	if len(id) == 0 {
		return errors.New("查询出的内容为空")
	}
	err = json.Unmarshal([]byte(id), jsons)
	if err != nil {
		// 可能是数据库中存储的单双引号异常导致的，此处进行替换后再次尝试
		if len(id) > 3 {
			if id[:2] == "\"{" {
				// 移除两侧的双引号
				id = id[1 : len(id)-1]
			}
		}
		// 双引号替换为 \"
		id = strings.ReplaceAll(id, "\"", "\\\"")
		// 单引号替换为双引号
		id = strings.ReplaceAll(id, "'", "\"")
		err = json.Unmarshal([]byte(id), jsons)
		if err != nil {
			return err
		}
	}
	return nil
}
